package com.ja.sevice.impl;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.ja.config.WebsiteStateConfig;
import com.ja.dao.AdminMapper;
import com.ja.dao.AgencyCenterMapper;
import com.ja.dao.DamalMapper;
import com.ja.dao.LiushuiMapper;
import com.ja.dao.LuckyCountMapper;
import com.ja.dao.SystemConfigMapper;
import com.ja.dao.UserAgentMapper;
import com.ja.dao.UserMapper;
import com.ja.domain.Agent;
import com.ja.domain.AgentLink;
import com.ja.domain.Damal;
import com.ja.domain.Liushui;
import com.ja.domain.LuckyCount;
import com.ja.domain.PagingData;
import com.ja.domain.ParkedDomains;
import com.ja.domain.User;
import com.ja.domain.Vip;
import com.ja.sevice.IUserService;
import com.ja.util.DateUtil;

@Service
public class UserServiceImpl implements IUserService {

	@Autowired
	public UserMapper userMapper;

	@Autowired
	private DamalMapper damalMapper;
	
	@Autowired
	private LiushuiMapper liushuiMapper;
	
	@Autowired
	private AdminMapper adminMapper;
	
	@Autowired
	private LuckyCountMapper luckyCountMapper;
	
	@Autowired
	private UserAgentMapper userAgentMapper;
	
	@Autowired
	private SystemConfigMapper systemConfigMapper;
	
	@Autowired
	private AgencyCenterMapper agencyCenterMapper;
	
	@Override
	public List<User> getAllUsers() {
		return userMapper.getAllUsers();
	}

	@Override
	public int register(HttpSession session,HttpServletRequest request,String name, String pass, String invitationCode, String qq, String ip,String telephone) {
		int fid = 0;
		User users = new User();
		if(Integer.parseInt(WebsiteStateConfig.configs.get("agent_flag")) == 2) {//使用第二套代理系统
			AgentLink a = agencyCenterMapper.pueryagencyInvitationCode(invitationCode);//根据邀请码查询当前代理
			if(a !=null) {
				users.setGamePlayer(a.getGamePlayer());//设置他是玩家还是代理
				User su = userMapper.checkUser(a.getUserName());//查询他的上级用户
				fid = a.getUserId();//添加用户的上级 通过邀请码
				users.setOdds(a.getInferiorOdds());//设置用户的赔率
				users.setRemainder(su.getRemainder()-a.getInferiorOdds());//设置自己还能调多少赔率
				if(su.getRemainder()-a.getInferiorOdds() <= 0) {
					users.setGamePlayer(0);//当小于等于0的时候  不能在是代理了 只能成为玩家
				}
			}else {
				try {
					String refCode = (String) session.getAttribute("refCode");//拿到用户当前访问的连接
					refCode.split("\\?");//拆分报错就不是用户的推广连接 有可能是总代理的代理连接
					if (refCode != null) { 
						String scheme = request.getScheme();//拿到用户访问的协议
						if(scheme != null) {
							if("http".equals(scheme) || "https".equals(scheme)) {//判断用户的协议
								AgentLink a1 = agencyCenterMapper.pueryagencyLinks("http://" + refCode);//根据连接查询用户的代理连接
								if(a1 != null) {
									users.setGamePlayer(a1.getGamePlayer());//设置他是玩家还是代理
									fid = a1.getUserId();//添加用户的上级 通过代理连接
									User su = userMapper.checkUser(a1.getUserName());//查询他的上级用户
									users.setOdds(a1.getInferiorOdds());//设置用户的赔率
									users.setRemainder(su.getRemainder()-a1.getInferiorOdds());//设置自己还能调多少赔率
									if(su.getRemainder()-a1.getInferiorOdds() <= 0) {
										users.setGamePlayer(0);//当小于等于0的时候  不能在是代理了 只能成为玩家
									}
								}
							}else {System.out.println("没有匹配到相关协议-------注册------"+scheme);}
						}
					}
				} catch (Exception e) {
					users.setRemainder(Double.parseDouble(WebsiteStateConfig.configs.get("minimumOdds")));//当上面两个都没走的时候 说明这个用户没有代理  所以他是最大的
					users.setGamePlayer(1);
					users.setOdds(0.0000);//设置用户的赔率
					fid = fId(request);//如果上面两个都没有匹配上那么就有可能是 总代理 的  如果不是总代理的  那么则返回0
				}
			}
		}else {//使用第一套代理系统
			try {
				String refCode = (String) session.getAttribute("refCode");//拿到用户当前访问的连接
				refCode.split("\\?");//拆分报错就不是用户的推广连接 有可能是总代理的代理连接
				if (refCode != null) { 
					String scheme = request.getScheme();//拿到用户访问的协议
					if(scheme != null) {
						if("http".equals(scheme) || "https".equals(scheme)) {//判断用户的协议
							User u = userAgentMapper.findUserByIcode("http://" + refCode);//根据连接查询用户的代理连接
							if(u != null) {
								fid = u.getId();//添加用户的上级 通过代理连接
							}
						}else {System.out.println("没有匹配到相关协议-------注册---使用第一套代理系统---"+scheme);}
					}
				}
			} catch (Exception e) {
				fid = fId(request);//如果没有那就是总代理了
			}
		}
		String md5 = DigestUtils.md5DigestAsHex(pass.getBytes());
		String pwd = DigestUtils.md5DigestAsHex(md5.getBytes());
		Double initBalance = Double.parseDouble(WebsiteStateConfig.configs.get("huiyuanchushijine"));
		users.setName(name);
		users.setNicheng(name);
		users.setAvatar("img/user.jpg");
		users.setPass(pwd);
		users.setBalance(initBalance);
		users.setFid(fid);
		users.setTelephone(telephone);
		users.setQq(qq);
		users.setVip("VIP1");
		users.setRegisterIp(ip);
		users.setLastIp(ip);
		users.setRegisterTime(DateUtil.getCurrTime());
		users.setLastTime(DateUtil.getCurrTime());
		users.setNotTime("未登录0天");
		users.setCreatetime(DateUtil.getCurrTime());
		users.setState(1);
		System.out.println(users.toString());
		int num = userMapper.register(users);

		/** 根据当前名称查询帐号信息 */
		User user = userMapper.checkUser(name);
		// 打码
		Damal damal = new Damal();
		damal.setHuiyuanzh(name);
		damal.setCreatetime(user.getCreatetime());
		damal.setTikuansx(0.00);
		damal.setUserid(user.getId());
		damalMapper.addamal(damal);
		
		//幸运抽奖
		LuckyCount counts = new LuckyCount();
		counts.setName(user.getName());
		counts.setCount(0);
		counts.setCreateTime(DateUtil.getCurrTime());
		counts.setUserid(user.getId());
		luckyCountMapper.addLuckyCount(counts);
		return num;
	}


	@Override
	public int register2(HttpSession session,HttpServletRequest request,String name, String pass, String invitationCode, String ip) {
		int fid = 0;
		User users = new User();
		if(Integer.parseInt(WebsiteStateConfig.configs.get("agent_flag")) == 2) {//使用第二套代理系统
			AgentLink a = agencyCenterMapper.pueryagencyInvitationCode(invitationCode);//根据邀请码查询当前代理
			if(a !=null) {
				users.setGamePlayer(a.getGamePlayer());//设置他是玩家还是代理
				User su = userMapper.checkUser(a.getUserName());//查询他的上级用户
				fid = a.getUserId();//添加用户的上级 通过邀请码
				users.setOdds(a.getInferiorOdds());//设置用户的赔率
				users.setRemainder(su.getRemainder()-a.getInferiorOdds());//设置自己还能调多少赔率
				if(su.getRemainder()-a.getInferiorOdds() <= 0) {
					users.setGamePlayer(0);//当小于等于0的时候  不能在是代理了 只能成为玩家
				}
			}else {
				try {
					String refCode = (String) session.getAttribute("refCode");//拿到用户当前访问的连接
					refCode.split("\\?");//拆分报错就不是用户的推广连接 有可能是总代理的代理连接
					if (refCode != null) {
						String scheme = request.getScheme();//拿到用户访问的协议
						if(scheme != null) {
							if("http".equals(scheme) || "https".equals(scheme)) {//判断用户的协议
								AgentLink a1 = agencyCenterMapper.pueryagencyLinks("http://" + refCode);//根据连接查询用户的代理连接
								if(a1 != null) {
									users.setGamePlayer(a1.getGamePlayer());//设置他是玩家还是代理
									fid = a1.getUserId();//添加用户的上级 通过代理连接
									User su = userMapper.checkUser(a1.getUserName());//查询他的上级用户
									users.setOdds(a1.getInferiorOdds());//设置用户的赔率
									users.setRemainder(su.getRemainder()-a1.getInferiorOdds());//设置自己还能调多少赔率
									if(su.getRemainder()-a1.getInferiorOdds() <= 0) {
										users.setGamePlayer(0);//当小于等于0的时候  不能在是代理了 只能成为玩家
									}
								}
							}else {System.out.println("没有匹配到相关协议-------注册------"+scheme);}
						}
					}
				} catch (Exception e) {
					users.setRemainder(Double.parseDouble(WebsiteStateConfig.configs.get("minimumOdds")));//当上面两个都没走的时候 说明这个用户没有代理  所以他是最大的
					users.setGamePlayer(1);
					users.setOdds(0.0000);//设置用户的赔率
					fid = fId(request);//如果上面两个都没有匹配上那么就有可能是 总代理 的  如果不是总代理的  那么则返回0
				}
			}
		}else {//使用第一套代理系统
			try {
				String refCode = (String) session.getAttribute("refCode");//拿到用户当前访问的连接
				refCode.split("\\?");//拆分报错就不是用户的推广连接 有可能是总代理的代理连接
				if (refCode != null) {
					String scheme = request.getScheme();//拿到用户访问的协议
					if(scheme != null) {
						if("http".equals(scheme) || "https".equals(scheme)) {//判断用户的协议
							User u = userAgentMapper.findUserByIcode("http://" + refCode);//根据连接查询用户的代理连接
							if(u != null) {
								fid = u.getId();//添加用户的上级 通过代理连接
							}
						}else {System.out.println("没有匹配到相关协议-------注册---使用第一套代理系统---"+scheme);}
					}
				}
			} catch (Exception e) {
				fid = fId(request);//如果没有那就是总代理了
			}
		}
		String md5 = DigestUtils.md5DigestAsHex(pass.getBytes());
		String pwd = DigestUtils.md5DigestAsHex(md5.getBytes());
		Double initBalance = Double.parseDouble(WebsiteStateConfig.configs.get("huiyuanchushijine"));
		users.setName(name);
		users.setNicheng(name);
		users.setAvatar("img/user.jpg");
		users.setPass(pwd);
		users.setBalance(initBalance);
		users.setFid(fid);
		users.setVip("VIP1");
		users.setRegisterIp(ip);
		users.setLastIp(ip);
		users.setRegisterTime(DateUtil.getCurrTime());
		users.setLastTime(DateUtil.getCurrTime());
		users.setNotTime("未登录0天");
		users.setCreatetime(DateUtil.getCurrTime());
		users.setState(1);
		System.out.println(users.toString());
		int num = userMapper.register(users);

		/** 根据当前名称查询帐号信息 */
		User user = userMapper.checkUser(name);
		// 打码
		Damal damal = new Damal();
		damal.setHuiyuanzh(name);
		damal.setCreatetime(user.getCreatetime());
		damal.setTikuansx(0.00);
		damal.setUserid(user.getId());
		damalMapper.addamal(damal);

		//幸运抽奖
		LuckyCount counts = new LuckyCount();
		counts.setName(user.getName());
		counts.setCount(0);
		counts.setCreateTime(DateUtil.getCurrTime());
		counts.setUserid(user.getId());
		luckyCountMapper.addLuckyCount(counts);
		return num;
	}

	/**
	 *返回这个用户的上级  总代理的
	 * @return
	 */
	public int fId(HttpServletRequest request) {
		int fid = 0;
		//当上面根据问号拆分的时出现异常则说名 用户时直接使用域名访问的 根据域名查询是否是总代理的下级
		List<ParkedDomains> parkedDomains = systemConfigMapper.findAllParkedDomains1(null, request.getServerName(),null);
		if (parkedDomains.size() > 0) {
			for (ParkedDomains pd : parkedDomains) {
				if (request.getServerName().equalsIgnoreCase(pd.getDomain())) {
					String agents = pd.getDefaultAgency();//获取总代理的用户名
					Agent agent = userAgentMapper.findAgent(agents);//查找总代理
					if (agent != null) {
						fid = agent.getId();//添加用户的上级   这个是总代理 通过总代理域名连接过来的
					}
				} 
			}
		}
		return fid;
	}

	@Override
	public User checkUser(String name) {
		User iuser = userMapper.checkUser(name);
		return iuser;
	}

	@Override
	public User login(String name, String pass) {
		User userr = userMapper.login(name, pass);
		return userr;
	}

	@Override
	public int userTryplay(User user) {
		user.setNicheng(user.getName());
		user.setAvatar("img/user.jpg");
		user.setBalance(Double.parseDouble(WebsiteStateConfig.configs.get("shiwanchushijine")));
		user.setRegisterTime(DateUtil.getCurrTime());
		user.setLastTime(DateUtil.getCurrTime());
		user.setNotTime("未登录0天");
		user.setCreatetime(DateUtil.getCurrTime());
		user.setState(2);
		user.setOdds(0.0000);
		return userMapper.userTryplay(user);
	}

	@Override
	public Double getAllAgentRebateTotal() {
		return userMapper.getAllAgentRebateTotal();
	}

	@Override
	public void delUser(Integer id) {
		userMapper.delUser(id);
	}

	@Override
	public User getUserByid(Integer id) {
		return userMapper.getUserByid(id);
	}

	@Override
	public List<User> getAllAgent() {
		return userMapper.getAllAgent();
	}

	public void updBlance(int id, double balance) {
		User user = new User();
		user.setId(id);
		user.setBalance(balance);
		userMapper.updateUserInfo(user);
	}

	@Override
	public List<User> timingRecovery() {
		return userMapper.timingRecovery();
	}

	@Override
	public void timeDeleting(Integer id) {
		userMapper.timeDeleting(id);
	}

	@Override
	public int[] getUserCount() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		int count1 = userMapper.getAgentOrUserCount(1);//代理 
		int count2 = userMapper.getAgentOrUserCount(0);//会员
		int count3 = count2 + count1; //用户总数
		int count4 = userMapper.getRegisterCount(sdf.format(new Date()));//今日注册
		int count5 = userMapper.getRegisterCount(sdf.format(DateUtils.addDays(new Date(), -1)).split(" ")[0]);//昨日注册
		double count6 = userMapper.getAllUserBalance();//用户余额
		int[] counts = new int[6];
		counts[0]=count1;
		counts[1]=count2;
		counts[2]=count3;
		counts[3]=count4;
		counts[4]=count5;
		counts[5]=(int)(count6);
		return counts;
	}

	@Override
	public int updateMoney(User user, Liushui l) {
		user.setCreatetime(DateUtil.getCurrTime());
		int a = userMapper.updateUserInfo(user);
		int b = liushuiMapper.addUserFlowingWaterRecrod(l);
		return a + b;
	}

	@Override
	public int updateUserInfo(User user) {
		user.setCreatetime(DateUtil.getCurrTime());
		return userMapper.updateUserInfo(user);
	}

	@Override
	public int findDatabaseCounts(String dataBaseName) {
		Integer count = adminMapper.findDatabaseCounts(dataBaseName);
		 if(count>24000) {
			 Integer id = adminMapper.findDatabaseLimit(dataBaseName);
			 adminMapper.deleteData(id,dataBaseName);
		 }
		return 0;
	}

	@Override
	public int findAllUserCounts(String name, String ip, String bankCard, String cname) {
		return userMapper.findAllUserCounts(name, ip, bankCard, cname);
	}

	@Override
	public List<User> findAllUsers(PagingData paging,String ip,String bankCard,String cname) {
		return userMapper.findAllUsers(paging, ip, bankCard, cname);
	}

	@Override
	public List<String> promotionLinks() {
		return userMapper.promotionLinks();
	}

	public static boolean takeInverse = true;

	// 根据ip添加游客 为什么不根据Session添加游客，因为用户可能创建多个Session
	public void addTourists(String ip, String page) {
		
	}

	@Override
	public List<User> findByTimeOrNameAllUsers(String startTime, String endTime, String userName) {
		//userMapper.findByTimeOrNameAllUsers(startTime, endTime, userName);
		User user = new User();
		user.setCreatetime(startTime);
		user.setRegisterTime(endTime);
		user.setName(userName);
		return userMapper.findByTimeOrNameAllUsers(user);
	}

	@Override
	public int vip(Integer id, String name) {
		//根据会员统计他的历史充值金额
		if(id == null && name == null) {
			return 0;
		}
		Double totalSum = userMapper.Statistics(id, name);//统计会员总充值金额
		if(totalSum == null) {
			return 0;
		}
		List<Vip> vip = userMapper.queryVip();//查询会员vip对照表
		Vip vi = null;
		for (Vip v : vip) {
			if((double)totalSum >= (double)v.getAmountOfMoney()) {
				vi = v;
			}
		}
		int num = userMapper.upDataVip(id, name, vi);
		return num;
	}

	@Override
	public int transferSubordinate(String name, String cname, String odds) {
		//先查询出转到这个的代理信息
		User user = userMapper.checkUser(name);//查询传入的代理
		//查询被转移的下级
		User u = userMapper.checkUser(cname);//查询传入的下级用户
		if(u == null || user == null) {
			return -4;//没有这个用户
		}
		if(odds == null && "".equals(odds)) {
			return -1;//用户的赔率不能为空
		}
		NumberFormat nf= NumberFormat.getPercentInstance();	//将百分比转成 数字
		try {
			Number m = nf.parse(odds);
			DecimalFormat df = new DecimalFormat("#0.00000");
			String str = df.format(m);
			Double oddss = Double.parseDouble(str);
			System.err.println(oddss+"----设置的赔率------上级可调动的赔率------"+user.getRemainder());
			if(oddss > user.getRemainder()) {
				return -2;//赔率不能大于代理可调动的赔率
			}
			return userMapper.upDataAgen(u.getId(), user.getId(), oddss,user.getRemainder()- oddss);
		} catch (ParseException e) {
			return -3;//设置的赔率格式不对
		}
		
	}
}
